<template>
    <div class="container">
        <t-chat :data="chat_msgs" class="chat" @clear="clearConfirm" :clear-history="chat_msgs.length > 0 && !loading">
            <!-- 操作按钮 -->


            <template #actions="{ item, index }">
                <t-chat-action :content="item.content" :operation-btn="['good', 'bad', 'replay', 'copy', 'delete']"
                    @operation="handleOperation" />
            </template>
            <template #datetime="{ item }">{{ item.create_at }}</template>
            <!-- 底部输入框 -->
            <template #footer>
                <t-chat-sender v-model="query" :textarea-props="{ placeholder: '请输入消息...' }" :loading="loading" focu
                    @send="inputEnter" @file-select="fileSelect" @stop="onStop">
                    <template #suffix="{ renderPresets }">
                        <component :is="renderPresets([])" />
                    </template>
                </t-chat-sender>
            </template>
        </t-chat>
    </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue';

// 输入与状态
const query = ref('');
const loading = ref(false);

// 聊天消息列表
const chat_msgs = ref([
    {
        avatar: 'http://192.168.0.91:8092/assets/sb-02f58d81.png',
        content: '你好，我是的你的AI助理，请提问吧！',
        role: 'assistant',
        create_at: new Date().toLocaleString(),
    }
]);

// 模拟 AI 流式回复（打字机效果）
const inputEnter = async () => {
    if (loading.value) return;
    const userQuery = query.value.trim();
    if (!userQuery) return;

    // 清空输入
    query.value = '';
    loading.value = true;

    // 添加用户消息
    chat_msgs.value.unshift({
        avatar: 'http://192.168.0.91:8092/assets/bd-4eb60740.png',
        content: userQuery,
        role: 'user',
        create_at: new Date().toLocaleString(),
    });

    // 创建 AI 消息对象（用于流式输出）
    const aiMsg = {
        avatar: 'http://192.168.0.91:8092/assets/chat-1eaa07c9.png',
        content: '',
        role: 'assistant',
        create_at: new Date().toLocaleString(),
    };
    chat_msgs.value.unshift(aiMsg);

    try {
        const response = await fetch('http://192.168.0.91:50080/api/v1/chatbot/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json',
            },
            body: JSON.stringify({
                message: userQuery,
                model: 'gpt-4o-mini',
                clear_history: false,
            }),
        });

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const reader = response.body?.getReader();
        if (!reader) {
            throw new Error('No stream available');
        }

        const decoder = new TextDecoder('utf-8');
        let buffer = ''; // 用于拼接未完整解析的行

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            buffer += decoder.decode(value, { stream: true });

            // 按行分割（SSE 以 \n 分隔）
            const lines = buffer.split('\n');
            buffer = lines.pop() || ''; // 保留不完整的最后一行

            for (const line of lines) {
                // 只处理以 "data: " 开头的行
                if (line.startsWith('data: ')) {
                    const jsonString = line.slice(6).trim(); // 去掉 "data: "
                    if (!jsonString || jsonString === '[DONE]') continue;

                    try {
                        const data = JSON.parse(jsonString);
                        const token = data.content || ''; // 你的字段是 content
                        if (token) {
                            aiMsg.content += token;
                            // 触发 Vue 响应式更新
                            chat_msgs.value = [...chat_msgs.value];
                            // 可选：滚动到底部
                            nextTick(() => {
                                const container = document.querySelector('.t-chat__list');
                                if (container) {
                                    container.scrollTop = container.scrollHeight;
                                }
                            });
                        }
                    } catch (e) {
                        console.warn('Failed to parse JSON:', jsonString);
                    }
                }
                // 忽略其他类型行（如 event:、id: 等）
            }
        }
    } catch (err: any) {
        console.error('Stream error:', err);
        aiMsg.content = `❌ 机器人出错: ${err.message}`;
        chat_msgs.value = [...chat_msgs.value];
    } finally {
        loading.value = false;
    }
};

// 其他事件处理
const fileSelect = (file: File) => {
    console.log('文件上传:', file);
};

const onStop = () => {
    loading.value = false;
    console.log('停止发送');
};

const handleOperation = (type: string, options: any) => {
    console.log('操作:', type, options);
};

// 清空消息
const clearConfirm = function () {
    chat_msgs.value = [chat_msgs.value[chat_msgs.value.length - 1]];
};
</script>

<style lang="scss" scoped>
.container {
    display: flex;
    justify-content: center;

}

.chat {
    // background-color: #f9fafa;
    padding: 10px;
    height: 80vh;
    width: 95%;
}
</style>

<!-- curl -X 'POST' \
'http://192.168.0.91:50080/api/v1/chatbot/chat' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"message": "你好",
"model": "gpt-4o-mini",
"clear_history": false
}' -->

<!-- data: {"content": ""}

data: {"content": "你好"}

data: {"content": "！"}

data: {"content": "有什么"}

data: {"content": "我"}

data: {"content": "可以"}

data: {"content": "帮助"}

data: {"content": "你"}

data: {"content": "的吗"}

data: {"content": "？"}

data: {"content": "无"}

data: {"content": "论"}

data: {"content": "是"}

data: {"content": "关于"}

data: {"content": "编"}

data: {"content": "程"}

data: {"content": "、"}

data: {"content": "技术"}

data: {"content": "问题"}

data: {"content": "，"}

data: {"content": "还是"}

data: {"content": "其他"}

data: {"content": "主题"}

data: {"content": "，都"}

data: {"content": "可以"}

data: {"content": "问"}

data: {"content": "我"}

data: {"content": "！"} -->
